<?php

declare(strict_types=1);

namespace App\Orchid\Screens\Media;

use Orchid\Attachment\Models\Attachment;
use Orchid\Screen\Actions\Button;
use Orchid\Screen\Actions\DropDown;
use Orchid\Screen\Actions\Link;
use Orchid\Screen\Actions\ModalToggle;
use Orchid\Screen\Components\Cells\DateTimeSplit;
use Orchid\Screen\Fields\Group;
use Orchid\Screen\Fields\Input;
use Orchid\Screen\Fields\Upload;
use Orchid\Screen\Layouts\Modal;
use Orchid\Screen\Layouts\Table;
use Orchid\Screen\Screen;
use Orchid\Screen\TD;
use Orchid\Support\Facades\Alert;
use Orchid\Support\Facades\Layout;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class MediaListScreen extends Screen
{
    /**
     * Fetch data to be displayed on the screen.
     *
     * @return array
     */
    public function query(): iterable
    {
        return [
            'attachments' => Attachment::filters()
                ->defaultSort('id', 'desc')
                ->paginate()
        ];
    }

    /**
     * The name of the screen displayed in the header.
     *
     * @return string|null
     */
    public function name(): ?string
    {
        return '媒体库管理';
    }

    /**
     * The screen's action buttons.
     *
     * @return \Orchid\Screen\Action[]
     */
    public function commandBar(): iterable
    {
        return [
            ModalToggle::make('上传文件')
                ->modal('uploadModal')
                ->icon('bs.cloud-upload')
                ->method('upload'),
        ];
    }

    /**
     * The screen's layout elements.
     *
     * @return \Orchid\Screen\Layout[]|string[]
     */
    public function layout(): iterable
    {
        return [
            Layout::table('attachments', [
                TD::make('id', 'ID')
                    ->sort()
                    ->cantHide()
                    ->filter(Input::make()),

                TD::make('original_name', '文件名')
                    ->sort()
                    ->cantHide()
                    ->filter(Input::make())
                    ->render(function (Attachment $attachment) {
                        return Link::make($attachment->original_name)
                            ->href($attachment->url())
                            ->target('_blank');
                    }),

                TD::make('mime', '文件类型')
                    ->sort()
                    ->filter(Input::make()),

                TD::make('size', '文件大小')
                    ->sort()
                    ->render(function (Attachment $attachment) {
                        return $this->formatBytes($attachment->size);
                    }),

                TD::make('created_at', '上传时间')
                    ->usingComponent(DateTimeSplit::class)
                    ->sort()
                    ->defaultHidden(),

                TD::make('updated_at', '更新时间')
                    ->usingComponent(DateTimeSplit::class)
                    ->sort()
                    ->defaultHidden(),

                TD::make(__('Actions'))
                    ->align(TD::ALIGN_CENTER)
                    ->width('100px')
                    ->render(fn (Attachment $attachment) => DropDown::make()
                        ->icon('bs.three-dots-vertical')
                        ->list([
                            Link::make(__('View'))
                                ->href($attachment->url())
                                ->target('_blank')
                                ->icon('bs.eye'),

                            Button::make(__('Delete'))
                                ->icon('bs.trash3')
                                ->confirm('确定要删除这个文件吗？')
                                ->method('remove', [
                                    'id' => $attachment->id,
                                ]),
                        ])),
            ]),

            Layout::modal('uploadModal', Layout::rows([
                Upload::make('attachment')
                    ->title('选择文件')
                    ->help('支持上传图片、文档等文件')
                    ->maxFiles(10)
                    ->acceptedFiles('image/*,application/pdf,.doc,.docx,.xls,.xlsx,.txt'),
            ]))
                ->title('上传文件')
                ->applyButton('上传'),
        ];
    }

    /**
     * 上传文件
     *
     * @param Request $request
     *
     * @return void
     */
    public function upload(Request $request)
    {
        $request->validate([
            'attachment' => 'required|array',
            'attachment.*' => 'file|max:10240', // 10MB
        ]);

        $uploadedCount = 0;
        foreach ($request->file('attachment', []) as $file) {
            $attachment = new Attachment([
                'name' => $file->getClientOriginalName(),
                'original_name' => $file->getClientOriginalName(),
                'mime' => $file->getClientMimeType(),
                'extension' => $file->getClientOriginalExtension(),
                'size' => $file->getSize(),
            ]);

            $attachment->path = $file->store('attachments', 'public');
            $attachment->save();
            $uploadedCount++;
        }

        Alert::info("成功上传 {$uploadedCount} 个文件");
    }

    /**
     * 删除文件
     *
     * @param Request $request
     *
     * @return void
     */
    public function remove(Request $request)
    {
        $attachment = Attachment::findOrFail($request->get('id'));
        
        // 删除物理文件
        if ($attachment->path && Storage::disk('public')->exists($attachment->path)) {
            Storage::disk('public')->delete($attachment->path);
        }
        
        // 删除数据库记录
        $attachment->delete();

        Alert::info('文件已删除');
    }

    /**
     * 格式化文件大小
     *
     * @param int $bytes
     * @return string
     */
    private function formatBytes(int $bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        
        for ($i = 0; $bytes > 1024 && $i < count($units) - 1; $i++) {
            $bytes /= 1024;
        }
        
        return round($bytes, 2) . ' ' . $units[$i];
    }
}